package com.yesway.arc_menu.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;

import com.yesway.arc_menu.R;

import static com.yesway.arc_menu.view.ArcMenu.Position.RIGHT_BOTTOM;

/**
 * @Description
 * @Author guojingbu
 * @Date 2019/1/27
 * @Update
 */

public class ArcMenu extends ViewGroup implements View.OnClickListener {

    public static final int POS_LEFT_TOP = 0;
    public static final int POS_LEFT_BOTTOM = 1;
    public static final int POS_RIGHT_TOP = 2;
    public static final int POS_RIGHT_BOTTOM = 3;

    private Position mPosition = Position.RIGHT_BOTTOM;
    /**
     * 菜单的半径
     */
    private int mRadius;

    /**
     * 菜单的当前状态
     */
    private Status mcurrStatus = Status.CLOSE;
    /**
     * 中间按钮的引用
     */
    private View mCbtn;

    private OnMenuItemClickListener mMenuItemClickListener;

    public void setmMenuItemClickListener(OnMenuItemClickListener mMenuItemClickListener) {
        this.mMenuItemClickListener = mMenuItemClickListener;
    }

    @Override
    public void onClick(View v) {
//        mCbtn = findViewById(R.id.id_button);
//        if(mCbtn==null){
//            mCbtn = getChildAt(0);
//        }
        rotateCButton(v, 0f, 360f, 300);
        toggleMenu(300);


    }

    /**
     * 切换菜单
     *
     * @param duration
     */
    public void toggleMenu(int duration) {

        int childCount = getChildCount();
        for (int i = 0; i < childCount - 1; i++) {
            final View childView = getChildAt(i + 1);
            childView.setVisibility(View.VISIBLE);
            //end 0 0
            //start
            int cl = (int) (mRadius * Math.sin(Math.PI / 2 / (childCount - 2) * i));
            int ct = (int) (mRadius * Math.cos(Math.PI / 2 / (childCount - 2) * i));
            int xflag = 1;
            int yflag = 1;
            if (mPosition == Position.LEFT_TOP || mPosition == Position.LEFT_BOTTOM) {
                xflag = -1;
            }
            if (mPosition == Position.LEFT_TOP || mPosition == Position.RIGHT_TOP) {
                yflag = -1;
            }

            AnimationSet animationSet = new AnimationSet(true);
            Animation tranAnim = null;
            if (mcurrStatus == Status.CLOSE) { // to open
                tranAnim = new TranslateAnimation(xflag * cl, 0, yflag * ct, 0);
                childView.setClickable(true);
                childView.setFocusable(true);
            } else { //to close
                tranAnim = new TranslateAnimation(0, xflag * cl, 0, yflag * ct);
                childView.setClickable(false);
                childView.setFocusable(false);
            }

            tranAnim.setFillAfter(true);
            tranAnim.setDuration(duration);
            tranAnim.setStartOffset(100*i/childCount);
            tranAnim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    if (mcurrStatus == Status.CLOSE) {
                        childView.setVisibility(View.GONE);
                    }

                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });

            RotateAnimation rotateAnimation = new RotateAnimation(0, 720, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation.setDuration(duration);
            rotateAnimation.setFillAfter(true);
            animationSet.addAnimation(rotateAnimation);
            animationSet.addAnimation(tranAnim);
            childView.startAnimation(animationSet);
            final int pos = i+1;
            childView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    if(mMenuItemClickListener!=null){
                        mMenuItemClickListener.onItemClick(childView,pos);
                    }
                    changeStatus();
                    menuItemAnim(pos-1);
                }
            });

        }
        changeStatus();

    }

    /**
     * 添加点击条目的点击动画
     * @param pos
     */

    private void menuItemAnim(int pos) {

        for(int i =0;i<getChildCount()-1;i++){
            View childView = getChildAt(i + 1);

            if(i==pos){
                childView.startAnimation(scaleBigAnim(300));
            }else{
                childView.startAnimation(scaleSamllAnim(300));
            }
            childView.setClickable(false);
            childView.setFocusable(false);
        }
    }

    private Animation scaleSamllAnim(int duration) {
        ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 0.0f, 1.0f, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
        AnimationSet animationSet = new AnimationSet(true);
        animationSet.addAnimation(scaleAnimation);
        animationSet.addAnimation(alphaAnimation);
        animationSet.setDuration(duration);
        animationSet.setFillAfter(true);
        return animationSet;
    }

    /**
     * 点击当前的item放大和透明度降低的动画
     * @param duration
     * @return
     */

    private Animation scaleBigAnim(int duration) {
        ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 4.0f, 1.0f, 4.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
        AnimationSet animationSet = new AnimationSet(true);
        animationSet.addAnimation(scaleAnimation);
        animationSet.addAnimation(alphaAnimation);
        animationSet.setDuration(duration);
        animationSet.setFillAfter(true);
        return animationSet;
    }

    /**
     * 切换菜单打开关闭状态
     */
    private void changeStatus() {
        mcurrStatus = (mcurrStatus == Status.CLOSE ? Status.OPEN : Status.CLOSE);
    }

    /**
     * 中间按钮旋转动画
     *
     * @param v
     * @param start
     * @param end
     * @param duration
     */
    private void rotateCButton(View v, float start, float end, int duration) {
        RotateAnimation animation = new RotateAnimation(start, end, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(duration);
        animation.setFillAfter(true);
        v.startAnimation(animation);
    }

    /**
     * 菜单的位置枚举类
     */
    public enum Position {
        LEFT_TOP, LEFT_BOTTOM, RIGHT_TOP, RIGHT_BOTTOM
    }

    /**
     * 菜单的状态
     */
    public enum Status {
        OPEN, CLOSE
    }

    public ArcMenu(Context context) {
        this(context, null);
    }

    public ArcMenu(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ArcMenu(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mRadius = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100,
                context.getResources().getDisplayMetrics());
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ArcMenu, defStyleAttr, 0);

        int pos = a.getInt(R.styleable.ArcMenu_position, POS_RIGHT_BOTTOM);
        switch (pos) {
            case POS_LEFT_TOP:
                mPosition = Position.LEFT_TOP;

                break;
            case POS_LEFT_BOTTOM:
                mPosition = Position.LEFT_BOTTOM;
                break;
            case POS_RIGHT_TOP:
                mPosition = Position.RIGHT_TOP;
                break;
            case POS_RIGHT_BOTTOM:
                mPosition = Position.RIGHT_BOTTOM;
                break;
        }

        mRadius = (int) a.getDimension(R.styleable.ArcMenu_radius, mRadius);

        Log.e("ArcMenu", "mRadius = " + mRadius + "mPostion = " + mPosition);

        a.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            //测量子view的尺寸。
            measureChild(getChildAt(i), widthMeasureSpec, heightMeasureSpec);
        }


        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed) {
            layoutCbutton();

            int childCount = getChildCount();
            for (int i = 0; i < childCount - 1; i++) {
                View child = getChildAt(i + 1);
                child.setVisibility(View.GONE);
                int childWidth = child.getMeasuredWidth();
                int childHeight = child.getMeasuredHeight();

                int cl = (int) (mRadius * Math.sin(Math.PI / 2 / (childCount - 2) * i));
                int ct = (int) (mRadius * Math.cos(Math.PI / 2 / (childCount - 2) * i));
                //左下 右下
                if (mPosition == Position.LEFT_BOTTOM || mPosition == Position.RIGHT_BOTTOM) {

                    ct = getMeasuredHeight() - childHeight - ct;
                }
                //右上 右下
                if (mPosition == Position.RIGHT_TOP || mPosition == RIGHT_BOTTOM) {
                    cl = getMeasuredWidth() - childWidth - cl;

                }

                child.layout(cl, ct, cl + childWidth, ct + childHeight);
            }
        }

    }

    /**
     * 定位主菜单按钮
     */
    private void layoutCbutton() {
        mCbtn = getChildAt(0);
        int width = 0;
        int height = 0;
        if (mCbtn != null) {
            mCbtn.setOnClickListener(this);
            width = mCbtn.getMeasuredWidth();
            height = mCbtn.getMeasuredHeight();
        }
        //定位cbutton的位置
        int l = 0;
        int t = 0;
        switch (mPosition) {
            case LEFT_TOP:
                l = 0;
                t = 0;

                break;
            case LEFT_BOTTOM:
                l = 0;
                t = getMeasuredHeight() - height;

                break;
            case RIGHT_TOP:
                l = getMeasuredWidth() - width;
                t = 0;
                break;
            case RIGHT_BOTTOM:
                l = getMeasuredWidth() - width;
                t = getMeasuredHeight() - height;
                break;

        }


        mCbtn.layout(l, t, l + width, t + height);

    }

    /**
     * 判断菜单是否为打开状态
     * @return
     */
    public boolean isOpen(){

        return mcurrStatus==Status.OPEN;
    }

    /**
     * 菜单点击条目回调接口
     */
    public interface OnMenuItemClickListener {

        void onItemClick(View view, int index);
    }
}
